import {
  Button,
  Form,
  FormItem,
  Image,
  ImagePreviewGroup,
  Modal,
  RadioButton,
  RadioGroup,
  Space,
  Textarea,
  TypographyText
} from 'ant-design-vue'
import { Moment } from 'moment'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'

import { riverApi } from '@/apis'
import { WithdrawDetail } from '@/apis/riverTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import {
  bus,
  download,
  downloadWithoutName,
  formatDate,
  isValueEmpty,
  optionsToMap
} from '@/utils'

import {
  billTypeOptions,
  forceOptions,
  OCROptions,
  paymentOptions,
  statusOptions
} from '../constants'
import FinanceRejectDialog from './components/FinanceRejectDialog'

export default defineComponent({
  name: 'RvWithdrawVerify',
  setup() {
    const tableRef = ref({} as ProTableRef)
    const monthRange = ref<Moment[]>([])
    const statusCur = ref(-1)
    const awaitAuditCount = ref(0)
    const awaitReceiveCount = ref(0)
    const optionItemCur = ref({} as WithdrawDetail)
    const rejectDlgRef = ref(null)
    const showRemarkDlg = ref(false)
    const { showConfirm, showInfo } = useDialog()
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '服务商名称',
              field: 'purchaserName',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '提交申请日期',
              field: 'timeRange',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  valueFormat: 'x',
                  keys: ['submitDateStart', 'submitDateEnd']
                }
              }
            },
            {
              title: '提现月份',
              field: 'monthRange',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  value: monthRange,
                  mode: ['month', 'month'],
                  placeholder: ['开始月份', '结束月份'],
                  format: 'YYYY-MM',
                  valueFormat: 'x',
                  onPanelChange: (val: Moment[]) => {
                    monthRange.value = val
                  },
                  onChange: () => {
                    monthRange.value = []
                  },
                  keys: ['monthBegin', 'monthEnd']
                }
              }
            },
            {
              title: '发票种类',
              field: 'invoiceType',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: billTypeOptions,
                props: {
                  placeholder: '全部',
                  allowClear: true
                }
              }
            },
            {
              title: '快递单号',
              field: 'logisticNo',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              title: '是否强制完成',
              field: 'isForceComplete',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: forceOptions,
                props: {
                  placeholder: '全部',
                  allowClear: true
                }
              }
            },
            {
              title: '是否打款',
              field: 'isPay',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                options: paymentOptions,
                props: {
                  placeholder: '全部',
                  allowClear: true
                }
              }
            },
            {
              title: '结算单号',
              field: 'settleNo',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '请输入',
                  allowClear: true
                }
              }
            },
            {
              slots: {
                default: () => {
                  return (
                    <Space>
                      <Button type="primary" htmlType="submit">
                        查询
                      </Button>
                      <Button
                        htmlType="reset"
                        onClick={() => {
                          monthRange.value = []
                        }}
                      >
                        重置
                      </Button>
                    </Space>
                  )
                }
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 150,
          resizable: true
        },
        checkboxConfig: {
          showHeader: true,
          range: true
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            type: 'seq',
            width: 50,
            title: '序号'
          },
          {
            title: '服务商名称',
            field: 'purchaserName',
            width: 150
          },
          {
            title: '原结算单号',
            field: 'oldSettleNo',
            width: 200
          },
          {
            title: '结算单号',
            field: 'settleNo',
            width: 200
          },
          {
            title: '提现金额',
            field: 'amount',
            width: 100,
            formatter: ({ cellValue }) => {
              return '￥' + cellValue
            }
          },
          {
            title: '提现月份',
            field: 'withdrawDate'
          },
          {
            title: '是否打款',
            field: 'isPay',
            formatter: ({ cellValue }) => {
              return optionsToMap(paymentOptions)[cellValue]
            },
            width: 80
          },
          {
            title: '发票凭证',
            width: 270,
            slots: {
              default: 'billImages'
            }
          },
          {
            title: '状态',
            field: 'status',
            formatter: ({ cellValue }) => {
              return optionsToMap(statusOptions)[cellValue]
            }
          },
          {
            title: 'OCR识别结果',
            field: 'ocrResult',
            formatter: ({ cellValue }) => {
              return optionsToMap(OCROptions)[cellValue]
            }
          },
          {
            title: '备注',
            field: 'ocrRemark',
            slots: {
              default: 'ocrRemarkText'
            }
          },
          {
            title: '发票类型',
            field: 'invoiceType',
            formatter: ({ cellValue }) => {
              return optionsToMap(billTypeOptions)[cellValue]
            }
          },
          {
            title: '快递单号',
            field: 'logisticNo'
          },
          {
            title: '物流状态',
            field: 'trace',
            minWidth: 200
          },
          {
            title: '提交申请时间',
            field: 'submitTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '审核时间',
            field: 'checkTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '强制完成人员',
            field: 'forceCompleteUserName'
          },
          {
            title: '审核人',
            field: 'updateUserName'
          },
          {
            title: '是否强制完成',
            field: 'isForceComplete',
            width: 100,
            formatter: ({ cellValue }) => {
              return optionsToMap(forceOptions)[cellValue]
            }
          },
          {
            title: '最新驳回时间',
            field: 'checkRejectTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss']
          },
          {
            title: '备注',
            field: 'comments'
          },
          {
            title: '操作',
            width: 170,
            fixed: 'right',
            slots: {
              default: 'operation'
            }
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              if (!isValueEmpty(monthRange.value)) {
                form.withdrawDateStart = formatDate(
                  monthRange.value[0],
                  'yyyy-MM'
                )
                form.withdrawDateEnd = formatDate(
                  monthRange.value[1],
                  'yyyy-MM'
                )
              } else {
                form.withdrawDateStart = null
                form.withdrawDateEnd = null
              }
              const data = await riverApi.getWithdrawList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                ...form,
                status: statusCur.value != -1 ? statusCur.value : null
              })
              awaitAuditCount.value = data.unCheckNum
              awaitReceiveCount.value = data.unReceiveNum
              return data.pager
            }
          }
        }
      }
    } as ProTableProps)

    onMounted(() => {
      bus.on('refreshWidthdrawList', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    //获取选中的项
    function getSelectedItems() {
      return tableRef.value.table?.getCheckboxRecords()
    }

    function batchDisabled() {
      return !(getSelectedItems()?.length != 0)
    }

    const router = useRouter()

    //查看详情/审核
    function handleDetail(item: WithdrawDetail) {
      router.push({
        name: 'RvFinanceBillDetail',
        query: {
          id: item.id
        }
      })
    }

    //驳回理由
    function handleRejectReason(item: WithdrawDetail) {
      // //@ts-ignore
      // rejectDlgRef.value.open(item.id, true)
      showInfo(item.rejectReason)
    }

    //下载结算单
    async function handleDowanloadReceipt(item: WithdrawDetail) {
      try {
        tableRef.value.showLoading()
        const res = await riverApi.dowanloadReceipt(item.id)
        download(res, '结算单')
        tableRef.value.refresh()
      } finally {
        tableRef.value.hideLoading()
      }
    }

    //重新生成结算单
    function handleRecreateReceipt(item: WithdrawDetail) {
      showConfirm({
        content: '是否重新生成结算单？',
        onOk: async () => {
          try {
            tableRef.value.showLoading()
            await riverApi.recreateReceipt(item.id)
            tableRef.value.refresh()
          } finally {
            tableRef.value.hideLoading()
          }
        }
      })
    }

    //强制完成
    function handleForce(item: WithdrawDetail) {
      showConfirm({
        content:
          '点击确认后，该结算单状态会改成已打款。金额会由可提现金额变成累计提现金额。',
        onOk: async () => {
          try {
            tableRef.value.showLoading()
            await riverApi.forceCompleteReceipt(item.id)
            tableRef.value.refresh()
          } finally {
            tableRef.value.hideLoading()
          }
        }
      })
    }
    //备注
    function handleRemark(item: WithdrawDetail) {
      optionItemCur.value.id = item.id
      showRemarkDlg.value = true
    }

    async function handleRemarkConfirm() {
      try {
        await riverApi.remark(
          optionItemCur.value.id,
          optionItemCur.value.logisticComment
        )
        showRemarkDlg.value = false
        tableRef.value.refresh()
      } finally {
      }
    }

    //历史记录
    function handleHistory(item: WithdrawDetail) {
      router.push({
        name: 'RvWithdrawHistory',
        query: {
          id: item.id
        }
      })
    }

    //确认签收
    function handleReceived(item: WithdrawDetail) {
      showConfirm({
        content: '是否确认签收发票？',
        onOk: async () => {
          try {
            await riverApi.batchSignReceive([item.id])
            tableRef.value.refresh()
          } finally {
          }
        }
      })
    }

    //导出Excel
    async function handleExportExcel() {
      const { form } = tableRef.value.table.getProxyInfo()!
      try {
        tableRef.value.showLoading()
        const res = await riverApi.exportExcel(form)
        download(res, '提现结算审核')
        tableRef.value.refresh()
      } finally {
        tableRef.value.hideLoading()
      }
    }

    //批量审核通过
    function handleBatchAudit() {
      const ids = getSelectedItems().map(item => {
        return item.id
      })
      showConfirm({
        content: '是否批量通过审核？',
        onOk: async () => {
          try {
            tableRef.value.showLoading()
            await riverApi.batchAgree(ids)
            tableRef.value.refresh()
          } finally {
            tableRef.value.hideLoading()
          }
        }
      })
    }

    //批量签收发票
    function handleBatchSignReceive() {
      const ids = getSelectedItems().map(item => {
        return item.id
      })
      showConfirm({
        content: '是否批量签收发票？',
        onOk: async () => {
          try {
            tableRef.value.showLoading()
            await riverApi.batchSignReceive(ids)
            tableRef.value.refresh()
          } finally {
            tableRef.value.hideLoading()
          }
        }
      })
    }

    //批量确认打款
    function handleBatchPayConfirm() {
      const ids = getSelectedItems().map(item => {
        return item.id
      })
      showConfirm({
        content: '是否批量确认打款？',
        onOk: async () => {
          try {
            tableRef.value.showLoading()
            await riverApi.batchPayConfirm(ids)
            tableRef.value.refresh()
          } finally {
            tableRef.value.hideLoading()
          }
        }
      })
    }

    //批量下载发票
    async function handleBatchDowanload() {
      const ids = getSelectedItems().map(item => {
        return item.id
      })
      try {
        tableRef.value.showLoading()
        const res = await riverApi.batchDownInvoice(ids)
        downloadWithoutName(res, '发票凭证.zip')
        tableRef.value.refresh()
      } finally {
        tableRef.value.hideLoading()
      }
    }

    return {
      statusCur,
      tableRef,
      tableConfig,
      awaitAuditCount,
      awaitReceiveCount,
      optionItemCur,
      showRemarkDlg,
      rejectDlgRef,
      handleDetail,
      handleRemark,
      handleHistory,
      handleRejectReason,
      handleReceived,
      batchDisabled,
      handleBatchAudit,
      handleBatchSignReceive,
      handleBatchPayConfirm,
      handleBatchDowanload,
      handleExportExcel,
      handleDowanloadReceipt,
      handleRecreateReceipt,
      handleRemarkConfirm,
      handleForce
    }
  },
  render() {
    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => {
              return (
                <div>
                  <RadioGroup
                    v-model:value={this.statusCur}
                    onChange={() => {
                      this.tableRef.refresh()
                    }}
                  >
                    <RadioButton value={-1}>全部</RadioButton>
                    <RadioButton value={0}>发票待上传</RadioButton>
                    <RadioButton value={4}>{`待审核${
                      this.awaitAuditCount
                        ? '(' + this.awaitAuditCount + ')'
                        : ''
                    }`}</RadioButton>
                    <RadioButton value={2}>{`发票待签收${
                      this.awaitReceiveCount
                        ? '(' + this.awaitReceiveCount + ')'
                        : ''
                    }`}</RadioButton>
                    <RadioButton value={6}>发票已签收</RadioButton>
                    <RadioButton value={5}>审核通过</RadioButton>
                    <RadioButton value={1}>驳回申请</RadioButton>
                  </RadioGroup>

                  <Space style={{ marginLeft: '50px' }}>
                    <Button onClick={this.handleExportExcel}>导出Excel</Button>
                    {this.statusCur == 4 ? (
                      <Button
                        disabled={this.batchDisabled()}
                        onClick={this.handleBatchAudit}
                        type="primary"
                      >
                        批量审核通过
                      </Button>
                    ) : null}
                    {this.statusCur == 2 ? (
                      <Button
                        disabled={this.batchDisabled()}
                        onClick={this.handleBatchSignReceive}
                        type="primary"
                      >
                        批量签收发票
                      </Button>
                    ) : null}
                    {this.statusCur == 5 || this.statusCur == 6 ? (
                      <Button
                        disabled={this.batchDisabled()}
                        onClick={this.handleBatchPayConfirm}
                        type="primary"
                      >
                        批量确认打款
                      </Button>
                    ) : null}

                    <Button
                      disabled={this.batchDisabled()}
                      onClick={this.handleBatchDowanload}
                      type="primary"
                    >
                      批量下载发票
                    </Button>
                  </Space>
                </div>
              )
            },
            billImages: ({ row }) => (
              <ImagePreviewGroup>
                <div>
                  {row.invoices?.split(',').map(item => {
                    return <Image style={{ height: '60px' }} src={item}></Image>
                  })}
                </div>
              </ImagePreviewGroup>
            ),
            ocrRemarkText: ({ row }) => (
              <div>
                <span>
                  {row.ocrRemark?.split('').map((item, index) => {
                    const differFontIndexes =
                      row.differFontIndex !== null && row.differFontIndex !== ''
                        ? row.differFontIndex.split(',').map(Number)
                        : []
                    return (
                      <span
                        style={{
                          color:
                            differFontIndexes.length > 0 &&
                            differFontIndexes.includes(index)
                              ? 'red'
                              : 'inherit'
                        }}
                      >
                        {item}
                      </span>
                    )
                  })}
                </span>
              </div>
            ),
            operation: ({ row }) => (
              <div>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleDowanloadReceipt(row)}
                >
                  下载结算单
                </Button>
                <Button
                  v-show={
                    (row.status == 0 || row.status == 1) && row.isResettle == 0
                  }
                  type="link"
                  size="small"
                  onClick={() => this.handleRecreateReceipt(row)}
                >
                  重新生成结算单
                </Button>
                <Button
                  v-show={row.status == 5 || row.status == 2 || row.status == 6}
                  type="link"
                  size="small"
                  onClick={() => this.handleDetail(row)}
                >
                  查看详情
                </Button>
                <Button
                  v-show={row.status == 4}
                  type="link"
                  size="small"
                  onClick={() => this.handleDetail(row)}
                >
                  审核
                </Button>
                <Button
                  v-show={row.status == 2}
                  type="link"
                  size="small"
                  onClick={() => this.handleReceived(row)}
                >
                  确认签收
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleRemark(row)}
                >
                  备注
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleForce(row)}
                  disabled={row.isForceComplete == 1}
                >
                  {/* {row.isForceComplete === 0 ? '' : ''} */}
                  强制完成
                </Button>
                <Button
                  v-show={row.status == 2 || row.status == 6 || row.status == 1}
                  type="link"
                  size="small"
                  onClick={() => this.handleHistory(row)}
                >
                  历史记录
                </Button>
                <Button
                  v-show={row.status == 1}
                  type="link"
                  size="small"
                  onClick={() => this.handleRejectReason(row)}
                >
                  驳回理由
                </Button>
              </div>
            )
          }}
          {...this.tableConfig}
        />
        <FinanceRejectDialog ref="rejectDlgRef"></FinanceRejectDialog>
        <Modal
          v-model:visible={this.showRemarkDlg}
          width={400}
          destroyOnClose
          closable={false}
          onOk={this.handleRemarkConfirm}
        >
          <Form labelCol={{ span: 4 }}>
            <FormItem label={'备注'} required>
              <Textarea
                placeholder="请输入"
                maxlength={500}
                v-model:value={this.optionItemCur.logisticComment}
              />
            </FormItem>
          </Form>
        </Modal>
      </div>
    )
  }
})
